﻿/***************************************************
//  Copyright (c) Premium Tax Free 2011
***************************************************/

using System;
using System.Threading;

namespace PremierTaxFree.PTFLib.Threading
{
    public abstract class CycleWorkerBase
    {
        protected Thread m_Worker = null;
        public event ThreadExceptionEventHandler Error;
        public volatile bool Running;

        /// <summary>
        /// Sleep Time in milliseconds
        /// </summary>
        public int SleepTime { get; set; }

        public void Start(ThreadPriority priority)
        {
            Running = true;
            m_Worker = new Thread(RunThread);
            m_Worker.IsBackground = true;
            m_Worker.Priority = priority;
            m_Worker.Start();
        }

        public void Stop()
        {
            Running = false;
            if (m_Worker != null)
                m_Worker.Join(5000);
            m_Worker = null;
        }

        protected virtual void RunThread()
        {
            while (Running)
            {
                try
                {
                    ThreadFunction();
                }
                catch (ThreadAbortException)
                {
                    //Do nothing
                }
                catch (ThreadInterruptedException)
                {
                    //Do nothing
                }
                catch (Exception ex)
                {
                    if (Error != null)
                        Error(this, new ThreadExceptionEventArgs(ex));
                }
                finally
                {
                    Thread.Sleep(SleepTime);
                }
            }
        }

        protected abstract void ThreadFunction();
    }
}
